import React, { createContext, useContext, useCallback, useState, useMemo, useEffect } from 'react';
export interface FitnessData {
    id: number;
    height: number;
    weight: number;
    lungs_capacity: number;
    running_time: number;
    score: number;
}
interface FitnessContextType {
    fitnessData: FitnessData[];
    onAdd: (data: Omit<FitnessData, 'id' | 'score'>) => void;
    isLoading: boolean;
    setIsLoading: (loading: boolean) => void;
    onEdit: (id: number, field: keyof FitnessData, value: number) => void;
    onDelete: (id: number) => void;
    onScores: (id?: number, score?: number) => void;
    newData: {
        height: string;
        weight: string;
        lungs_capacity: string;
        running_time: string;
    };
    setNewData: (newData: FitnessContextType['newData']) => void;
    filter: {
        minScore: number;
        maxScore: number;
    };
    setFilter: (filter: { minScore: number; maxScore: number }) => void;
    filteredData: FitnessData[];
    groupedData: { name: string; value: number }[];
    autoCalculate:boolean;
    setAutoCalculate: React.Dispatch<React.SetStateAction<boolean>>;
    calculateScore:(data: Omit<FitnessData, 'id' | 'score'>) => number;

}
export const MockData: FitnessData[] = [
    { id: 1, height: 170, weight: 60, lungs_capacity: 1800, running_time: 120, score: 0 },
    { id: 2, height: 171, weight: 65, lungs_capacity: 2000, running_time: 210, score: 0 },
    { id: 3, height: 172, weight: 75, lungs_capacity: 1500, running_time: 310, score: 0 },
    { id: 4, height: 113, weight: 35, lungs_capacity: 250, running_time: 230, score: 0 },
    { id: 5, height: 114, weight: 25, lungs_capacity: 300, running_time: 330, score: 0 },
    { id: 6, height: 172, weight: 75, lungs_capacity: 1500, running_time: 310, score: 0 },
    { id: 7, height: 113, weight: 35, lungs_capacity: 250, running_time: 130, score: 0 },
    { id: 8, height: 114, weight: 25, lungs_capacity: 300, running_time: 133, score: 0 },
]
const FitnessContext = createContext<FitnessContextType>({} as FitnessContextType);

export const FitnessProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [fitnessData, setFitnessData] = useState<FitnessData[]>(MockData);
    const [isLoading, setIsLoading] = useState(true); // 新增加载状态
    //  添加自动计算开关状态（用于控制输入时是否实时计算）
    const [autoCalculate, setAutoCalculate] = useState(true);
    const [newData, setNewData] = useState<FitnessContextType['newData']>({
        height: '',
        weight: '',
        lungs_capacity: '',
        running_time: '',
    });
    const [filter, setFilter] = useState({
        minScore: 0,
        maxScore: 1000
    });
    const onAdd = useCallback((data: Omit<FitnessData, 'id' | 'score'>) => {
        setFitnessData(prev => [
            ...prev,
            {
                ...data,
                id: prev.length + 1,
                score: calculateScore(data)
            }
        ]);
    }, []);
    const onEdit = useCallback((id: number, field: keyof FitnessData, value: number) => {
        setFitnessData(prev =>
            prev.map(item =>
                item.id === id ? { ...item, [field]: value } : item
            )
        );
    }, []);

    const onDelete = useCallback((id: number) => {
        setFitnessData(prev => prev.filter(item => item.id !== id));
    }, []);

    const onScores = useCallback((id?: number, score?: number) => {
        setFitnessData(prev =>
            prev.map(item => {
                if (id && item.id !== id) return item;
                return {
                    ...item,
                    score: score !== undefined ? score : calculateScore(item)
                };
            })
        );
    }, []);

    const calculateScore = (data: Omit<FitnessData, 'id' | 'score'>) => {
        return Number(((data.lungs_capacity / data.weight) * (1000 / data.running_time) * 0.5).toFixed(2));
    };

    // 5. 使用useMemo优化计算属性（当前每次渲染都重新计算）
    const filteredData = useMemo(() =>
        fitnessData.filter(data =>
            data.score >= filter.minScore && data.score <= filter.maxScore
        ),
        [fitnessData, filter]
    );
    const groupedData = useMemo(() => [
        { name: '0-20', value: fitnessData.filter(d => d.score >= 0 && d.score <= 20).length },
        { name: '21-40', value: fitnessData.filter(d => d.score > 20 && d.score <= 40).length },
        { name: '41-60', value: fitnessData.filter(d => d.score > 40 && d.score <= 60).length },
        { name: '60+', value: fitnessData.filter(d => d.score > 60).length }
    ], [fitnessData])


    return (
        <FitnessContext.Provider value={{
            fitnessData,
            onAdd,
            onEdit,
            onDelete,
            onScores,
            newData,
            setNewData,
            filter,
            setFilter,
            filteredData,
            groupedData,
            isLoading,
            setIsLoading,
            autoCalculate,
            setAutoCalculate,
            calculateScore
        }}>
            {children}
        </FitnessContext.Provider>
    );
};

export const useFitness = () => useContext(FitnessContext);